<template>
  <div>
    <!-- 头部面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: './Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-button type="primary" @click="addRightuser = true">添加角色</el-button>
        <el-dialog title="提示" @close="addDialogRights" :visible.sync="addRightuser" width="30%">
          <!-- 角色提交表达单 -->
          <el-form :model="RightsForm" :rules="rules" ref="RightsForm" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="RightsForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="RightsForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addRightuser = false">取 消</el-button>
            <el-button type="primary" ref="a" @click="addRightuserPudata()">确 定</el-button>
          </span>
        </el-dialog>
      </el-row>
      <el-table :data="getroleslists" stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdtop', index1 === 0 ? '' : 'bdbottom', 'vcenter']"
              v-for="(itme1, index1) in scope.row.children" :key="itme1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, itme1.id)"> {{ itme1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="18">
                <!-- 二级权限 -->
                <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(itme2, index2) in itme1.children"
                  :key="itme2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removeRightById(scope.row, itme2.id)" type="success">{{ itme2.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="17">
                    <!-- 三级权限 -->
                    <el-tag v-for="(itme3, index3) in itme2.children" :key="itme3.id" type="warning" closable
                      @close="removeRightById(scope.row, itme3.id)">{{ itme3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="UoDateRightuser = true , UpDateUserid(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="DeleteRights(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 修改区 -->
      <el-dialog title="提示" :visible.sync="UoDateRightuser" width="30%">
          <!-- 角色提交表达单 -->
          <el-form :model="UpdateRightsForm" :rules="rules" ref="UpDateRightsForm" label-width="100px">
            <el-form-item v-show="false" label="角色ID" prop="roleId">
              <el-input v-model="UpdateRightsForm.roleId"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="UpdateRightsForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="UpdateRightsForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="UoDateRightuser = false">取 消</el-button>
            <el-button type="primary" ref="a" @click="UpDateRightuserPudata()">确 定</el-button>
          </span>
        </el-dialog>
      <!-- 分配权限面板 -->
      <el-dialog title="分配权限" @close="setRightsClosed" :visible.sync="showSetRightsDialogVisible" width="50%">
        <!-- 分配 -->
        <el-tree :data="rightsList" show-checkbox node-key="id" ref="treeRed" :default-checked-keys="defkeys"
          default-expand-all :props="defaultProps">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showSetRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 获取角色列表数据
      getroleslists: [],
      // 控制分配权限面板是否展示
      showSetRightsDialogVisible: false,
      // 获取权限列表所有数据
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点
      defkeys: [],
      // 当前即将分配的角色对象
      roleID: '',
      addRightuser: false,
      // 添加角色数据
      RightsForm: {
        roleName: '',
        roleDesc: ''
      },
      // 控制修改弹窗
      UoDateRightuser: false,
      // 修改表单的数据
      UpdateRightsForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度不能超过10不能小于3',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度不能超过10不能小于3',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.$message({
        message: '获取成功',
        type: 'success'
      })
      this.getroleslists = res.data
    },
    // 添加角色
    addRightuserPudata() {
      this.$refs.RightsForm.validate(async (value) => {
        if (!value) return this.$message.error('添加失败')
        console.log(value)
        const { data: res } = await this.$http.post('roles', this.RightsForm)
        if (res.meta.status !== 200) {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getRolesList()
          this.addRightuser = false
        }
      })
    },
    // 监听表单是否关闭
    addDialogRights() {
      this.$refs.RightsForm.resetFields()
    },
    // 根据id 删除对应的 权限
    async removeRightById(role, rightid) {
      // 弹窗是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      )
      if (res.meta.status != 200) return this$.message.error('删除失败')
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightsDialog(scope) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      this.defkeys = this.getLeafkeys(scope, this.defkeys)
      // 要分配角色的ud
      this.roleID = scope.id
      this.showSetRightsDialogVisible = true
    },
    // 通过递归的形式获取权限下的三级权限 id 并保存到数组中
    getLeafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getLeafkeys(element, arr)
      })
      return arr
    },
    // 监听分配权限对话框关闭事件
    setRightsClosed() {
      this.defkeys = []
    },
    // 获取选中的权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRed.getCheckedKeys(),
        ...this.$refs.treeRed.getHalfCheckedKeys()
      ]
      const ridss = keys.join(',')
      console.log(ridss)
      const { data: res } = await this.$http.post(`roles/${this.roleID}/rights`, { rids: ridss })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message({
        message: '分配成功',
        type: 'success'
      })
      this.showSetRightsDialogVisible = false
      this.getRolesList()
    },
    // 删除角色
    async DeleteRights(scope) {
      const confirmReRights = await this.$confirm(
        '此操作将永久删除该用户',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmReRights !== 'confirm') return this.$message.error('取消删除')
      // 请求删除请求
      const { data: res } = await this.$http.delete('roles/' + scope.id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      this.getRolesList()
    },
    async UpDateUserid(id) {
      const { data: res } = await this.$http.get('roles/' + id.id)
      this.UpdateRightsForm = res.data
    },
    // 修改角色
    UpDateRightuserPudata() {
      this.$refs.UpDateRightsForm.validate(async (value) => {
        if (!value) return
        const { data: res } = await this.$http.put('roles/' + this.UpdateRightsForm.roleId, {
          roleName: this.UpdateRightsForm.roleName,
          roleDesc: this.UpdateRightsForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.UoDateRightuser = false
        this.getRolesList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
